package com.smile.frame.config.es.config;


import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @author LGC
 * @date 2021/12/3 17:42
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(ElasticSearchConfig.class)
public class EsClient {


    @Bean
    public RestHighLevelClient getRestHighLevelClient(ElasticSearchConfig config) {
        log.info("ElasticSearchConfig:{}", config);

        //如果没配置密码就可以不用下面这两部
//        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
//        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

        List<String> uris = config.getUris();
        HttpHost[] hosts = new HttpHost[uris.size()];
        for (int i = 0; i < uris.size(); i++) {
            hosts[i] = HttpHost.create(uris.get(i));
        }
        RestClientBuilder builder = RestClient.builder(hosts);
        builder.setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder
                .setConnectTimeout(3000) // 10s连接超时
                .setSocketTimeout(5000) // 20s套接字超时
                .setConnectionRequestTimeout(1000)); // 请求超时
        // 没有密码可以不用这一个set
//                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
//            @Override
//            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
//                httpClientBuilder.disableAuthCaching();
//                return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
//            }
//        });

        return new RestHighLevelClient(builder);
    }

    private HttpHost buildHttpHost(String node) {
        String[] nodeInfo = node.split(":");
        return new HttpHost(nodeInfo[0].trim(), Integer.parseInt(nodeInfo[1].trim()), "http");
    }
}
